home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2650 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.5 KB  |  51 lines

  1. Newsgroups: comp.lang.c++
  2. Path: in2.uu.net!allegra!alice!bs
  3. From: bs@research.att.com (Bjarne Stroustrup <9758-26353> 0112760)
  4. Subject: Re: Smart Pointer Implementation & question
  5. Message-ID: <DLDw3H.7L1@research.att.com>
  6. Organization: Info. Sci. Div., AT&T Bell Laboratories, Murray Hill, NJ
  7. References: <4dfe36$d99@grid.direct.ca> <749@beech.ukc.ac.uk>
  8. Date: Thu, 18 Jan 1996 15:52:29 GMT
  9.  
  10.  
  11. Article 125614 of comp.lang.c++:
  12.  
  13. From: R.E.Jones@ukc.ac.uk (rej) writes
  14.  
  15.  > In article <4dfe36$d99@grid.direct.ca>, Ken Clark <ken@direct.ca> wrote:
  16.  > >Hi.  I have implemented a reference counting smart pointer class.  It works 
  17.  > >well, except that I can't get a basic behavior of normal pointers:
  18.  > >automatic casting of subclass pointers.
  19.  > 
  20.  > This is a well-known problem with smart pointers.
  21.  > 
  22.  > A good survey of the extent of the problem and possible solutions can be
  23.  > found in
  24.  > 
  25.  > @inproceedings{edel92b,
  26.  > author = "Daniel R. Edelson",
  27.  > title = "Smart Pointers: They're Smart, But They're Not Pointers",
  28.  > booktitle = "USENIX C++ Conference",
  29.  > year = 1992
  30.  > }
  31.  
  32. However, things have progressed since that paper was written.
  33.  
  34. The problem is discussed in sec15.9.1 of D&E. You need member templates.
  35. Here is the key example:
  36.  
  37. template<class T> class Ptr { // pointer to T
  38.     T* p;
  39. public:       
  40.     Ptr(T*);
  41.     template<class T2> operator Ptr<T2> () {
  42.         return Ptr<T2>(p); // works iff p can be
  43.                            // converted to a T2*
  44.     }
  45.     // ...
  46. };
  47.  
  48. That way, a Ptr<D> will convert to a Ptr<B> iff a D* converts to B*.
  49.  
  50.     - Bjarne
  51.